const Router = require('@koa/router')//导入路由包
const router = new Router();//实例化路由
const { UserModel }  = require('../database') 
const { where,Op} = require('sequelize')


router.get('/',(ctx, next) =>{
    ctx.body = `来到用户界面`
});

// 获取所有用户信息（分页查询）
router.get('/getAllUsersByPage', async (ctx, next) => {
    const { currentPage, pageSize, userName, type } = ctx.request.query;
    let offset = (currentPage - 1) * pageSize || 0;
    const condition1 = userName? { userName: { [Op.like]: `%${userName}%` } } : null;
    const condition2 = type? { type: { [Op.eq]: type } } : null;
    let result = await UserModel.findAndCountAll({
      where: Object.assign({}, condition1, condition2),
      order: [['createdAt', 'DESC']],
      offset,
      limit: parseInt(pageSize),
    });
    if (result.rows.length > 0) {
      ctx.body = { code: "200", data: result, message: "success" };
    } else {
      ctx.body = { code: "500", data: { message: "添加失败" }, message: "fail" };
    }
  });

//localhost:3000/user/login
router.post('/login', async (ctx) => {
    const { userName, password } = ctx.request.body;
    try {
        const result = await UserModel.findOne({ where: { userName, password } });
        if (result) {
            ctx.body = {
                code: 200,
                msg: '欢迎登录',
                data: result, // 返回用户数据
            };
        } else {
            ctx.body = {
                code: 500,
                msg: '登录失败，用户名或密码错误',
            };
        }
    } catch (error) {
        console.error('登录处理错误:', error); // 打印错误信息
        ctx.status = 500; // 设置响应状态为500
        ctx.body = {
            code: 500,
            msg: '服务器内部错误，请重试',
        };
    }
});






router.get('/register',(ctx, next) =>{
    const name = ctx.query.name
    ctx.body = `欢迎注册 ${name}`
});
module.exports = router; // 导出路由，以便在其他文件中使用